import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import {  Modal,Icon,Tabs,message,Table,Dropdown,Menu,Button,Input,Form ,Row,Col,Select,Switch,Popconfirm,Radio,DatePicker }from 'antd';
const Search = Input.Search;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import SearchPanel from '../common/SearchPanel';
import RemarkModal from '../common/RemarkModal';

import api from '../api';
import moment from 'moment';
import {bind_change, bind_toggle} from '../common/State';
const {RangePicker} = DatePicker;
import {
  ACCOUNT_ROLE_TYPE,
}from '../constants/index';


export default class AccountManageList extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
           page:1,
           total:1,
           pageSize:10,
           list:[],
           search:{},
           searchFlag:true,
           visible:false,
           resetpwdId:null,
           session:{},
           deleteModalVisible:false,
           selectedRowKeys:[],

        };
    }

     componentWillMount(){
      let {page,pageSize} = this.state;
      this.doFetch(page,pageSize);
    }
     componentWillReceiveProps(nextProps){
        //  let session = await this.props.route.session();
        // this.setState({
        //   session
        // })
    }
    //查询列表
    async doFetch(page,size){

      
      this.setState({
        searchFlag:true
      })
      let session = this.props.route.session;
      let {keyword} = this.state
      let result = await api('/system/accountManage/list',{pageNumber:page,pageSize:size,keyword:keyword});

      if(result.success){
          this.setState({
            total:result.data.totalItem,
            list:result.data.pageResult||[],
            page,
            searchFlag:false,
            pageSize:result.data.pageSize,
            session,
          });
      }else{
        this.setState({
          searchFlag:false,
          session
        })
        message.error(result.message)
      }

    }

    add(){
      this.context.router.push("/systemManage/accountManage/edit");
    }

    async onSearchKeyWords(){
      let page = 1; 
      let pageSize = 10;
      this.doFetch(page,pageSize);
      // let {keyword} = this.state
      // let result = await api('/system/accountManage/list',{pageNumber:page,pageSize:pageSize,keyword:keyword});

      // if(result.success){
      //     this.setState({
      //       total:result.data.totalItem,
      //       list:result.data.pageResult||[],
      //       page,
      //       searchFlag:false,
      //       pageSize:result.data.pageSize,
      //     });
      // }else{
      //   this.setState({
      //     searchFlag:false
      //   })
      //   message.error(result.message)
      // }
    }

    onSelectRows(selectedRowKeys, selectedRows){


       this.setState({
        selectedRowKeys,
        selectedRows
       })
    }



    //删除
    onSubmitDeleteConfirm(){
      this.setState({
        searchFlag:true,
      })
      let {selectAccount} = this.state;
      let id_list = [selectAccount.id];
      this.deleteRecord(id_list)        
    }

    async deleteRecord(id_list){
      let result = await api('/system/accountManage/delete',{id_list});
      if (result.success) {
        message.success('删除成功');
        let {page,pageSize,list} = this.state;
        if (list.length == 1) {
          page = page > 1?page-1 :page;
        }
        this.doFetch(page,pageSize);
      }else{
        message.error(result.message);
      }
      this.setState({
        deleteModalVisible:false,
        searchFlag:false,
      })
    }


    //批量删除
    async batchDelete(){
      let {selectedRows} = this.state;
      let id_list = [];
      selectedRows.map((record,index) =>{
        id_list.push(record.id);
      })

      let result = await api('/system/accountManage/delete',{id_list});
      if (result.success) {
        message.success('删除成功');
        let {page,pageSize,list} = this.state;
        if (list.length == 1) {
          page = page > 1?page-1 :page;
        }
        this.doFetch(page,pageSize);
      }else{
        message.error(result.message);
      }
      this.setState({
        deleteModalVisible:false,
        searchFlag:false,
        selectedRowKeys:[],
        selectedRows:[],
      })

    }






    //重置密码
    async onSubmitResetPasswordConfirm(){
      let {selectAccount} = this.state;
      let result = await api('/system/accountManage/resetPassword',{id:selectAccount.id,password:selectAccount.newPassword});
      this.setState({
        resetPasswordModalVisible:false,
        selectAccount:{}
      })

      if (result.success) {
        message.success("修改成功");
      }else{
        message.error(result.message);
      }
    }


    //修改账号状态
    async onSubmitChangeAccountConfirm(){
      let {selectAccount} = this.state;
      let result = await api('/system/accountManage/changeStatus',{active:selectAccount.active?false:true,id:selectAccount.id});

      this.setState({
        accountStatusModalVisible:false,
        selectAccount:{}
      })

      if (result.success) {
        message.success('修改成功');
        let {page,pageSize} = this.state;
        this.doFetch(page,pageSize);
      }else{
        message.error('修改失败');
      }
      
    }

    
    getTableHeader(){
      let {selectedRowKeys,pageSize} = this.state;
      if (selectedRowKeys.length > 0 ) {
        return(
            <div className="table-header">
              <p className="table-header-content" > 
                已选中{selectedRowKeys.length}/{pageSize}
                <span className="marginR10 marginL10">|</span>
                <Button
                  type="primary"
                  size="small"
                  onClick={this.batchDelete.bind(this)}
                >删除</Button>
                {/*<Button
                  type="primary"
                  className="marginL10"
                  size="small"
                >导出选中</Button>*/}
               </p>
            </div>
          )
      }else{
        return(
            <div className="table-header">
              <span className="table-header-content">已选中0/{pageSize}</span>
            </div>
          )
      }
    }
    

    
    //分页
    toPage({current:page,pageSize,total}){
      page = page;
      this.doFetch(page,pageSize);
    }

    
    render() {

        var {list, page,total,searchFlag,departmentList,search,pageSize,selectAccount,selectedRowKeys}=this.state;
        return (
            <div >
                {/*<NavBar navs={[{title:'社区信息'}]} />*/}
                <ContentBody className='container'>
                  <div>
                      <div style={{"float":"left"}}>账户管理</div>
                      <div>
                      <div className="text-right">
                        
                        

                        <Input
                            {...this::bind_change('keyword')}
                            placeholder="搜索关键字"
                            style={{"width":"120px"}}
                            className='marginR10'
                          />

                        <Button
                          type="primary"
                          icon="search"
                          onClick={this.onSearchKeyWords.bind(this)}
                          className="marginR10"
                        >搜索</Button>

                        <Button
                          type="primary"
                          onClick={this.add.bind(this)}
                        ><Icon type="plus" />添加账户</Button>
                      </div>

                        
                      </div>
                  </div>

                  <Table
                    bordered
                    title={this.getTableHeader.bind(this)}
                    columns={this.getColumns()}
                    simple
                    dataSource={list}
                    pagination={{
                      current:page,
                      total:total,
                      pageSize:pageSize,

                    }}
                    loading={searchFlag}
                    onChange={this.toPage.bind(this)}
                    scroll={{ x: 1000 }}
                    rowKey={(record,index) => index}
                    rowSelection={{
                      onChange:this.onSelectRows.bind(this),
                      selectedRowKeys,
                    }}
                    className='marginT20'
                  />

                  <Modal
                    title="重置密码"
                    visible={this.state.resetPasswordModalVisible}
                    onOk={this.onSubmitResetPasswordConfirm.bind(this)}
                    onCancel={() => {
                      this.setState({
                        resetPasswordModalVisible:false,
                      })
                    }}
                  > 
                    <Row span={16}>
                      <Col span={2} className="marginT5">新密码</Col>
                      <Col span={14}>
                        <Input
                          placeholder="请输入新密码"
                          {...this::bind_change('selectAccount.newPassword')}
                          type="password"
                        ></Input>
                      </Col>
                    </Row>
                    <p className="marginT10">重置后请告知员工，确保其正常登录</p>
                  </Modal>

                  <Modal
                    title="提示"
                    visible={this.state.accountStatusModalVisible}
                    onOk={this.onSubmitChangeAccountConfirm.bind(this)}
                    onCancel={() => {
                      this.setState({
                        accountStatusModalVisible:false,
                      })
                    }}
                  >
                    {selectAccount && selectAccount.active?
                      <p>停用后账号不能登录，确定要停用该账号？</p>
                      :
                      <p>确定要启用该账户吗？</p>
                    }
                  </Modal>

                  <Modal
                    title="提示"
                    visible={this.state.deleteModalVisible}
                    onOk={this.onSubmitDeleteConfirm.bind(this)}
                    onCancel={() => {
                      this.setState({
                        deleteModalVisible:false,
                      })
                    }}
                  >
                    <p>确定要删除选中的账号？</p>
                  </Modal>

                </ContentBody>
            </div>
        );
    }

    getColumns(){
      let {session} = this.state;
      let columns = [
            {
              title: '姓名',
              dataIndex: 'username',
              key: 'username',
              width:60,
            }, {
              title: '账号',
              dataIndex: 'account',
              key: 'account',
            }, {
              title: '公司',
              dataIndex: 'firm',
              key: 'firm',
            },{
              title: '部门',
              dataIndex: 'apartment',
              key: 'apartment',
            }, {
              title: '手机',
              dataIndex: 'cellphone',
              key: 'cellphone',
              width:100,
            },{
              title: '权限',
              dataIndex: 'role_type',
              key: 'role_type',
              render:(role_type) => {
                return ACCOUNT_ROLE_TYPE[role_type]
              }
            },{
              title: '状态',
              dataIndex: 'active',
              key: 'active',
              render:(active) =>{
                return active?"正常":"已停用";
              }
            },{
              title: '操作',
              key: 'action',
              fixed: 'right',
              width:220,
              render: (record) =>{
                if(!record.id) return;
                  return (
                        <span className={'table-operation'}>
                            <span>
                              <a
                                href='javascript:void 0'
                                onClick={() =>{
                                  this.context.router.push(`/systemManage/accountManage/edit?id=${record.id}`)
                                }}
                              >
                              编辑
                              </a>
                              <i className='separator'>|</i>

                              <a 
                                href='javascript:void 0'
                                onClick={() => {
                                  this.setState({
                                    resetPasswordModalVisible:true,
                                    selectAccount:record,
                                  })
                                }}
                                >
                                重置密码
                              </a>
                              <i className='separator'>|</i>

                              <a 
                                href='javascript:void 0'
                                onClick={() =>{
                                  this.setState({
                                    accountStatusModalVisible:true,
                                    selectAccount:record,
                                  })
                                }}
                                >
                                {
                                  record.active ? "停用账号":"启用账号"
                                }
                                
                              </a>
                              <i className='separator'>|</i>

                              <a 
                                href='javascript:void 0'
                                onClick={() =>{
                                  this.setState({
                                    deleteModalVisible:true,
                                    selectAccount:record,
                                  })
                                }}
                                >
                                删除账号
                              </a>
                            </span>
                        </span>
                      )
              } ,
            }
        ];

        return columns
    }
}
AccountManageList.contextTypes= { router: React.PropTypes.object.isRequired};
